package com.wss.lsl.lucene.demo;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class LuceneWriteWhenReading {

	public static final Analyzer analyzer = new IKAnalyzer();
	private static Directory directory1 = null;
	private static Directory directory2 = null;

	static {
		try {
			directory1 = FSDirectory.open(new File("d:\\index_"));
			directory2 = FSDirectory.open(new File("d:\\index_"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void write() {
		IndexWriter writer = null;
		try {
			for (int i = 0; i < 100; i++) {
				IndexWriterConfig writerConfig = new IndexWriterConfig(
						Version.LUCENE_35, analyzer);
				writer = new IndexWriter(directory1, writerConfig);
				int base = 0x4e00;
				Random random = new Random();
				for (int j = 0; j < 10; j++) {
					Document doc = new Document();
					doc.add(new NumericField("num", Field.Store.YES, true)
					.setIntValue(random.nextInt(10000)));
					doc.add(new Field("name", ""
							+ (char) (base + random.nextInt(10000)),
							Field.Store.YES, Field.Index.NOT_ANALYZED));
					writer.addDocument(doc);
				}
				System.out.println("write: " + i);
				writer.close();
				Thread.sleep(1000);
			}
			System.out.println("write done!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void read() {
		IndexReader reader = null;
		IndexSearcher searcher = null;
		try {
			reader = IndexReader.open(directory2);
			searcher = new IndexSearcher(reader);
			Query query = NumericRangeQuery.newIntRange("num", 1, 5000, true,
					true);
			for (int i = 0; i < 10; i++) {
				reader = searcher.getIndexReader();
				IndexReader tr = IndexReader.openIfChanged(reader);
				if(tr != null){
					reader.clone();
					reader = tr;
					searcher = new IndexSearcher(reader);
				}
				TopDocs hits = searcher.search(query, 100);
				System.out.println("Found " + hits.totalHits + " hits.");
				StringBuilder sb = new StringBuilder();
				for (ScoreDoc hit : hits.scoreDocs) {
					Document doc = searcher.doc(hit.doc);
					sb.setLength(0);
					for (Fieldable row : doc.getFields()) {
						sb.append(row.name());
						sb.append(": ");
						sb.append(row.stringValue());
						sb.append("\t");
					}
					System.out.println(sb.toString());
				}
				System.out.println("read: " + i);
				Thread.sleep(10000);
			}
			System.out.println("read done!");
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			try {
				if (searcher != null) {
					searcher.close();
				}
				if (reader != null) {
					reader.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	
	@Test
	public void test3(){
		try {
			Directory directory = FSDirectory.open(new File("d:\\index35\\index\\business"));
			IndexReader reader = IndexReader.open(directory);
			IndexSearcher searcher = new IndexSearcher(reader);
			Query query1 = null;
			QueryParser que = new MultiFieldQueryParser(Version.LUCENE_35,
					new String[]{"NAME", "CARD_ID", "JIGUAN"}, analyzer);
			query1 = que.parse("430524198810116377");// 此种查询排序更准确

			Query query2 = new TermQuery(new Term("TABLENAME", "ID_CARD_PT"));// 表名查询

			BooleanQuery bq = new BooleanQuery();// 实现与或的复合搜索
			if (query1 != null)
				bq.add(query1, BooleanClause.Occur.MUST);// 关键字
			bq.add(query2, BooleanClause.Occur.MUST);// 表名必须
			System.out.println(bq);
			TopScoreDocCollector collector = null;
			int returnCount = 100;
			collector = TopScoreDocCollector.create(returnCount, true);// 返回指定数量记录,true为按文档的序号排序
			searcher.search(bq, collector);

			int numTotalHits = collector.getTotalHits();// 查询到的总条数
			System.out.println("numTotalHits: " + numTotalHits);
			searcher.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Done!");
	}
}
